# -*- coding: utf-8 -*-
# @Time    : 2024/3/9 10:31
# @Author  : xh
# @FileName: run.py
# @Software: PyCharm
from datetime import datetime
import os

import pytest
import subprocess
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from common.handle_log import mylog
from common.handle_path import REPORT_DIR


# from pytest_allure import AllureTestReporter


# 邮件通知配置
def send_email(subject, body, to_email):
    from_email = "your_email@example.com"
    password = "your_email_password"

    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    server = smtplib.SMTP('smtp.example.com', 587)
    server.starttls()
    server.login(from_email, password)
    text = msg.as_string()
    server.sendmail(from_email, to_email, text)
    server.quit()


# 运行pytest并生成Allure报告
def run_tests():
    # 设置pytest选项
    pytest_args = [
        '--maxfail=5',  # 失败最大次数
        '--disable-warnings',  # 禁用警告
        '--alluredir=allure-results',  # Allure结果目录
        '--capture=no',  # 输出详细日志
        r'D:\study\gitee\API\testcases\test_user_query.py',  # 测试路径
    ]
    # 执行pytest测试
    result = subprocess.run(['pytest'] + pytest_args, capture_output=True, text=True,encoding='utf-8')
    if result.returncode == 0:
        mylog.info("所有测试通过")
    else:
        mylog.error("测试失败，查看详细日志")
        print(result.stdout)

    #生成Allure报告
    generate_allure_report()


# 生成Allure报告并保存到指定目录
def generate_allure_report():
    # 获取当前日期并生成动态报告名称
    current_date = datetime.now().strftime('%m-%d-%H-%M')
    report_output_dir = os.path.join(REPORT_DIR, current_date)
    # 检查目录是否存在，如果不存在则创建
    if not os.path.exists(report_output_dir):
        os.makedirs(report_output_dir)
    #因为是虚拟环境设置了环境变量直接allure所以采用绝对路径
    # 运行 Allure generate 命令，并指定输出目录
    subprocess.run([r'D:\soft\allure-2.34.0\bin\allure.bat', 'generate', "allure-results", '-o', report_output_dir])

    # 如果需要显示报告，可以在此调用 allure serve
    #subprocess.run([r'D:\soft\allure-2.34.0\bin\allure.bat', 'serve', report_output_dir])




# 发送邮件通知
def send_test_results_via_email():
    subject = "测试结果报告"
    body = "测试已完成，详情请查看 Allure 测试报告或 Jenkins 输出日志。"
    send_email(subject, body, "recipient@example.com")


# 主函数：集成所有功能
if __name__ == '__main__':
    run_tests()
    # send_test_results_via_email()
